package net.tv90.bfmccoreqqbot.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.tv90.bfmccoreqqbot.Main;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

/**
 * @author zyx
 * @date 2023/3/3 14:23
 */

public class HttpUtil {

    private static final Logger logger = Main.plugin.getLogger();
    private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
    private static RequestConfig requestConfig;

    static {
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
        Builder configBuilder = RequestConfig.custom();
        configBuilder.setConnectTimeout(60000);
        configBuilder.setSocketTimeout(70000);
        configBuilder.setConnectionRequestTimeout(30000);
        requestConfig = configBuilder.build();
    }

    public HttpUtil() {
    }

    public static JSONObject httpGet(String url) {
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                if (response.toString().startsWith("{")) {
                    return JSON.parseObject(response.toString());
                } else {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("data", response.toString());
                    return jsonObject;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static JSONObject httpPost(String url, String data) {
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            con.setDoOutput(true);

            con.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }

                return JSON.parseObject(response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * post,以 application/json 形式
     *
     * @param apiUrl
     * @param json
     * @return
     */
    public static String doPost(String apiUrl, String json) {
        long start = System.currentTimeMillis();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        int statusCode = -999;
        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            statusCode = response.getStatusLine().getStatusCode();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception var20) {
            logger.info("HttpUtil post error:" + var20.getMessage());
            var20.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException var19) {
                    var19.printStackTrace();
                }
            }

            //logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start});
        }

        return httpStr;
    }

    /**
     * Post方式
     *
     * @param apiUrl
     * @param json      json数据
     * @param headerMap 请求头
     * @return
     */
    public static String doPost(String apiUrl, String json, Map<String, String> headerMap) {
        long start = System.currentTimeMillis();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        int statusCode = -999;

        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            //循环增加header
            if (headerMap != null) {
                Iterator headerIterator = headerMap.entrySet().iterator();
                while (headerIterator.hasNext()) {
                    Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
                    httpPost.addHeader(elem.getKey(), elem.getValue());
                }
            }
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            statusCode = response.getStatusLine().getStatusCode();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception var20) {
            logger.info("HttpUtil post error:" + var20.getMessage());
            var20.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException var19) {
                    var19.printStackTrace();
                }
            }

            //logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start});
        }

        return httpStr;
    }

    /**
     * Post请求
     *
     * @param apiUrl 请求链接
     * @param params 请求类型：x-www-form-urlencoded
     * @return
     */
    public static String doPost(String apiUrl, Map<String, Object> params) {
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        String httpStr = null;
        int statusCode = -999;
        //创建http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpPost实例
        HttpPost httpPost = new HttpPost(apiUrl);
        try {
            httpPost.setConfig(requestConfig);
            List<NameValuePair> pairList = new ArrayList();
            Iterator i$ = params.entrySet().iterator();

            while (i$.hasNext()) {
                Entry<String, Object> entry = (Entry) i$.next();
                NameValuePair pair = new BasicNameValuePair((String) entry.getKey(), entry.getValue().toString());
                pairList.add(pair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            logger.info("HttpUtil发生错误:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //logger.info("request path:{}, param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, params.toString(), statusCode, httpStr, System.currentTimeMillis() - start});
        }

        return httpStr;
    }

    /**
     * @param url
     * @param params 带参数
     * @return
     */
    public static String doGet(String url, Map<String, Object> params) {
        long start = System.currentTimeMillis();
        StringBuffer param = new StringBuffer();
        int i = 0;
        for (Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
            String key = (String) i$.next();
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }

            param.append(key).append("=").append(params.get(key));
        }
        String apiUrl = url + param;
        String result = null;
        //创建一个httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        int statusCode = -999;
        try {
            HttpGet httpGet = new HttpGet(apiUrl);
            HttpResponse response = httpClient.execute(httpGet);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (Exception var18) {
            logger.info("httputil get error:" + var18.getMessage());
            var18.printStackTrace();
        } finally {
            if (httpClient != null) {
                //关闭流
                HttpClientUtils.closeQuietly(httpClient);
            }

            //logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start});
        }

        return result;
    }

    /**
     * 请求方式 Get
     *
     * @param url       请求链接
     * @param params    以 x-www-form-urlencoded
     * @param headerMap 请求头参数
     * @return
     */
    public static String doGet(String url, Map<String, Object> params, Map<String, String> headerMap) {
        long start = System.currentTimeMillis();
        StringBuffer param = new StringBuffer();
        int i = 0;

        for (Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
            String key = (String) i$.next();
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }

            param.append(key).append("=").append(params.get(key));
        }

        String apiUrl = url + param;
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        int statusCode = -999;

        try {
            HttpGet httpGet = new HttpGet(apiUrl);
            //循环增加header
            if (headerMap != null) {
                Iterator headerIterator = headerMap.entrySet().iterator();
                while (headerIterator.hasNext()) {
                    Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
                    httpGet.addHeader(elem.getKey(), elem.getValue());
                }
            }
            HttpResponse response = httpClient.execute(httpGet);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (Exception e) {
            logger.info("HttpUtil发生错误:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                HttpClientUtils.closeQuietly(httpClient);
            }

            //logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start});
        }
        return result;
    }
}

